<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="接口类型" prop="typeId">
        <el-select
          v-model="queryParams.typeId"
          placeholder="请选择接口类型"
          filterable
        >
          <el-option
            v-for="item in optionsType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="认证信息" prop="ttpMid">
        <el-select
          v-model="queryParams.ttpMid"
          placeholder="请选择认证信息"
          filterable
        >
          <el-option
            v-for="item in optionsManufacturer"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['ruoyi-managerapi:api:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ruoyi-managerapi:api:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ruoyi-managerapi:api:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['ruoyi-managerapi:api:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="apiList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" align="center" />
      <el-table-column
        label="接口名称"
        align="center"
        prop="name"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="接口类型"
        align="center"
        prop="typeIdResult"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="认证名称" align="center" prop="ttpMidResult" />
      <el-table-column
        label="请求路径"
        align="center"
        prop="urlPath"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="连接状态" align="center" prop="stateResult">
        <template #default="scope">
          <div :style="scope.row.stateStyle">{{ scope.row.stateResult }}</div>
        </template>
      </el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        width="250"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="250"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ruoyi-managerapi:api:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ruoyi-managerapi:api:remove']"
            >删除</el-button
          >
          <el-button
            link
            type="primary"
            @click="handleTestConnection(scope.row)"
            v-hasPermi="['ruoyi-managerapi:manufacturer:test']"
            ><el-icon><Odometer /></el-icon>测试</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改接口管理接口信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="apiRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="认证信息" prop="ttpMid">
          <el-select
            v-model="form.ttpMid"
            placeholder="请选择认证信息"
            filterable
          >
            <el-option
              v-for="item in optionsManufacturer"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="接口类型" prop="typeId">
          <el-select
            v-model="form.typeId"
            placeholder="请选择接口类型"
            filterable
          >
            <el-option
              v-for="item in optionsType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="接口名称" prop="name">
          <el-input
            v-model="form.name"
            type="textarea"
            placeholder="请输入接口名称"
          />
        </el-form-item>
        <el-form-item label="请求路径" prop="urlPath">
          <el-input
            v-model="form.urlPath"
            type="textarea"
            placeholder="请输入请求路径"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 测试对话框 -->
    <el-dialog :title="title" v-model="openTest" width="500px" append-to-body>
      <div style="height: 600px; overflow: scroll">{{ codeText }}</div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="onCopy"
            ><el-icon><DocumentCopy /></el-icon>复制</el-button
          >
          <el-button @click="cancelTest">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Api">
const arrayManufacturer = ref([]);
const optionsManufacturer = ref([]);
const arrayType = ref([]);
const optionsType = ref([]);
function getoptionsManufacturer(tempList) {
  optionsManufacturer.value = [];
  for (let i = 0; i < tempList.length; i++) {
    optionsManufacturer.value.push({
      label: tempList[i].name,
      value: tempList[i].id * 1,
    });
  }
}
function getoptionsType(tempList) {
  optionsType.value = [];
  tempList.forEach((item) => {
    optionsType.value.push({
      label: item.name,
      value: item.id * 1,
    });
  });
}
onMounted(() => {
  getListType();
});
function getListType() {
  let queryParams1 = {
    pageNum: 1,
    pageSize: 10000,
  };
  listType(queryParams1).then((response) => {
    console.log(response);
    getoptionsType(response.rows);
    arrayType.value = response.rows;
    getListManufacturer();
  });
}
function getListManufacturer() {
  let queryParams1 = {
    pageNum: 1,
    pageSize: 10000,
  };
  listManufacturer(queryParams1).then((response) => {
    getoptionsManufacturer(response.rows);
    arrayManufacturer.value = response.rows;
    getList();
  });
}

// 复制成功时的回调函数
async function onCopy() {
  try {
    await toClipboard(codeText.value);
    ElMessage({
      type: "success",
      message: "内容已复制到剪切板！",
      showClose: true,
    });
  } catch (e) {
    ElMessage({
      message: "抱歉，复制失败！",
      type: "error",
      showClose: true,
    });
  }
}
// 复制失败时的回调函数
function cancelTest() {
  openTest.value = false;
}
const openTest = ref(false);
const codeText = ref("");
function handleTestConnection(item) {
  apiState(item.id).then((response) => {
    console.log(response);
    codeText.value = JSON.stringify(response);
    openTest.value = true;

    if (response.code == 200) {
      ElMessage({
        type: "success",
        message: "测试连接--连接成功!",
        showClose: true,
      });
      item.state = 1;
    } else {
      ElMessage({
        message: "测试连接--连接失败!",
        type: "error",
        showClose: true,
      });
      item.state = 0;
    }
    if (item.id != null) {
      updateApi(item).then((response) => {
        getList();
      });
    }
  });
}

import {
  listApi,
  getApi,
  delApi,
  addApi,
  updateApi,
  apiState,
} from "@/api/ruoyi-managerapi/api";
import { listManufacturer } from "@/api/ruoyi-managerapi/manufacturer";
import { listType } from "@/api/ruoyi-managerapi/type";
import { ElMessage } from "element-plus";
import { onMounted } from "vue";
import useClipboard from "vue-clipboard3";
const { toClipboard } = useClipboard();

const { proxy } = getCurrentInstance();

const apiList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
  },
  rules: {},
});

const { queryParams, form, rules } = toRefs(data);

/** 查询接口管理接口信息列表 */
function getList() {
  loading.value = true;
  listApi(queryParams.value).then((response) => {
    apiList.value = response.rows;
    total.value = response.total;
    loading.value = false;

    apiList.value.forEach((item) => {
      arrayManufacturer.value.forEach((item2) => {
        if (item.ttpMid == item2.id) {
          item.ttpMidResult = item2.name;
        }
      });
      arrayType.value.filter((item3) => {
        if (item.typeId == item3.id) {
          item.typeIdResult = item3.name;
        }
      });
      if (item.state == 1) {
        item.stateResult = "正常";
        item.stateStyle = {
          color: "green",
        };
      } else {
        item.stateResult = "断开";
        item.stateStyle = {
          color: "red",
        };
      }
    });
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    urlPath: null,
    tTpMid: null,
    headers: null,
    paramType: null,
    typeId: null,
    modelId: null,
    state: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    createBy: null,
    documentPath: null,
    documentVersion: null,
  };
  proxy.resetForm("apiRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加接口管理接口信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getApi(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改接口管理接口信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["apiRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateApi(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addApi(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除接口管理接口信息编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delApi(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "ruoyi-managerapi/api/export",
    {
      ...queryParams.value,
    },
    `api_${new Date().getTime()}.xlsx`
  );
}
</script>
